import * as monaco from "monaco-editor";

/**
 * 配置Java语言支持
 */
export const configureJavaLanguage = () => {
    // 配置Java代码提示
    monaco.languages.registerCompletionItemProvider('java', {
        provideCompletionItems: (model, position) => {
            // 获取当前行的内容
            const textUntilPosition = model.getValueInRange({
                startLineNumber: position.lineNumber,
                startColumn: 1,
                endLineNumber: position.lineNumber,
                endColumn: position.column
            });

            const suggestions = [
                {
                    label: 'class',
                    kind: monaco.languages.CompletionItemKind.Class,
                    insertText: 'class ${1:name} {\n\t$0\n}',
                    insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
                    documentation: '创建一个新类',
                    range: {
                        startLineNumber: position.lineNumber,
                        endLineNumber: position.lineNumber,
                        startColumn: position.column - 'class'.length,
                        endColumn: position.column
                    }
                },
                {
                    label: 'public',
                    kind: monaco.languages.CompletionItemKind.Keyword,
                    insertText: 'public ',
                    documentation: '公共访问修饰符',
                    range: {
                        startLineNumber: position.lineNumber,
                        endLineNumber: position.lineNumber,
                        startColumn: position.column - 'public'.length,
                        endColumn: position.column
                    }
                },
                {
                    label: 'sout',
                    kind: monaco.languages.CompletionItemKind.Snippet,
                    insertText: 'System.out.println($0);',
                    insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
                    documentation: '输出到控制台',
                    range: {
                        startLineNumber: position.lineNumber,
                        endLineNumber: position.lineNumber,
                        startColumn: position.column - 'sout'.length,
                        endColumn: position.column
                    }
                },
                {
                    label: 'main',
                    kind: monaco.languages.CompletionItemKind.Snippet,
                    insertText: 'public static void main(String[] args) {\n\t$0\n}',
                    insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
                    documentation: '主方法',
                    range: {
                        startLineNumber: position.lineNumber,
                        endLineNumber: position.lineNumber,
                        startColumn: position.column - 'main'.length,
                        endColumn: position.column
                    }
                },
                {
                    label: 'if',
                    kind: monaco.languages.CompletionItemKind.Keyword,
                    insertText: 'if (${1:condition}) {\n\t$0\n}',
                    insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
                    documentation: 'if语句',
                    range: {
                        startLineNumber: position.lineNumber,
                        endLineNumber: position.lineNumber,
                        startColumn: position.column - 'if'.length,
                        endColumn: position.column
                    }
                },
                {
                    label: 'for',
                    kind: monaco.languages.CompletionItemKind.Snippet,
                    insertText: 'for (int ${1:i} = 0; ${1:i} < ${2:length}; ${1:i}++) {\n\t$0\n}',
                    insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
                    documentation: 'for循环',
                    range: {
                        startLineNumber: position.lineNumber,
                        endLineNumber: position.lineNumber,
                        startColumn: position.column - 'for'.length,
                        endColumn: position.column
                    }
                }
            ];

            return {
                suggestions: suggestions.filter(item =>
                    !textUntilPosition.trim() ||
                    item.label.toLowerCase().includes(textUntilPosition.trim().toLowerCase())
                )
            };
        },
        triggerCharacters: ['.', ' '] // 触发提示的字符
    });

    // 配置Java格式化规则
    monaco.languages.registerDocumentFormattingEditProvider('java', {
        provideDocumentFormattingEdits: (model) => {
            const text = model.getValue();

            const formatted = text
                // 处理空行（删除多余的空行，最多保留一个）
                .replace(/\n\s*\n\s*\n/g, '\n\n')

                // 处理大括号
                .replace(/\s*{\s*/g, ' {\n')
                .replace(/\s*}\s*/g, '\n}')

                // 处理小括号
                .replace(/\(\s+/g, '(')
                .replace(/\s+\)/g, ')')

                // 处理逗号后添加空格
                .replace(/,(\S)/g, ', $1')

                // 处理for循环中的分号
                .replace(/for\s*\(\s*/g, '\nfor (')
                .replace(/for\s*\((.*?)\)/g, (_match, content) => {
                    // 在for循环内部的分号后只添加空格，不换行
                    return 'for (' + content.replace(/;\s*/g, '; ') + ')';
                })

                // 处理分号（for循环之外的）
                .replace(/;(?![^(]*\))(?!\s*\n)/g, ';\n')  // 只在分号后面不是换行符时添加换行

                // 修改运算符前后的空格处理规则
                // 先处理复合运算符（+=, -=, ++, --等）
                .replace(/\s*([\+\-])\1\s*/g, '$1$1')  // 处理++和--
                .replace(/\s*([\+\-\*\/\%\=])\s*=/g, ' $1=')  // 处理+=, -=, *=, /=, %=
                // 再处理普通运算符
                .replace(/(?<![+\-])\s*([\+\-\*\/\%\=\>\<\!\&\|])\s*(?![+\-])/g, ' $1 ')

                // 处理if/for/while后的空格
                .replace(/(if|for|while)\(/g, '$1 (')

                // 分割成行并处理缩进
                .split('\n')
                .map((line, index, array) => {
                    // 计算当前行的缩进级别
                    let indentLevel = 0;
                    for (let i = 0; i < index; i++) {
                        indentLevel += (array[i].match(/{/g) || []).length;
                        indentLevel -= (array[i].match(/}/g) || []).length;
                    }

                    // 如果当前行有结束括号，减少缩进
                    if (line.trim().startsWith('}')) {
                        indentLevel--;
                    }

                    // 应用缩进
                    return '    '.repeat(Math.max(0, indentLevel)) + line.trim();
                })
                .join('\n')

                // 处理空行中的空格
                .replace(/^\s+$/gm, '');

            return [{
                range: model.getFullModelRange(),
                text: formatted
            }];
        }
    });
}; 